<?php
class iring
{
	static public function  str_normalizer($str)
	{					
	    $str = iring::strKhongdau($str);	    
	    $str = str_replace('.','-', $str);
	    $str = str_replace('%','-',$str);
	    $str = str_replace('#','-',$str);
	    $str = str_replace('?','-',$str);	
	    $str = str_replace('/','-',$str);
	    $str = str_replace('(','-',$str);
	    $str = str_replace(')','-',$str);
	    $str = str_replace('[','-',$str);
	    $str = str_replace(']','-',$str);
	    $str = str_replace('{','-',$str);
	    $str = str_replace('}','-',$str);
	    $str = str_replace('+','-',$str);
	    $str = str_replace('_','-',$str);
	    $str = str_replace(' ','-',$str);
		
	    $str = mb_strtolower($str, 'UTF-8');
	    $str = 'nhac-chuong-'.$str;	    
	    return $str;
	 	
	}

        static public function str_normalizer_c($str)
	{
	    $str = iring::strKhongdau($str);
	    $str = str_replace('.','-', $str);
	    $str = str_replace('%','-',$str);
	    $str = str_replace('#','-',$str);
	    $str = str_replace('?','-',$str);
	    $str = str_replace('/','-',$str);
	    $str = str_replace('(','-',$str);
	    $str = str_replace(')','-',$str);
	    $str = str_replace('[','-',$str);
	    $str = str_replace(']','-',$str);
	    $str = str_replace('{','-',$str);
	    $str = str_replace('}','-',$str);
	    $str = str_replace('+','-',$str);
	    $str = str_replace('_','-',$str);
	    $str = str_replace(' ','-',$str);
	    return $str;
	}
	
	static public function strKhongDau($str)
	{
		$marTViet=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă",
	                "ằ","ắ","ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề"
	                ,"ế","ệ","ể","ễ",
	                "ì","í","ị","ỉ","ĩ",
	                "ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
	                ,"ờ","ớ","ợ","ở","ỡ",
	                "ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
	                "ỳ","ý","ỵ","ỷ","ỹ",
	                "đ",
	                "À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
	                ,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
	                "È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
	                "Ì","Í","Ị","Ỉ","Ĩ",
	                "Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
	                ,"Ờ","Ớ","Ợ","Ở","Ỡ",
	                "Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
	                "Ỳ","Ý","Ỵ","Ỷ","Ỹ",
	                "Đ","?");
	
	    $marKoDau=array("a","a","a","a","a","a","a","a","a","a","a"
	                    ,"a","a","a","a","a","a",
	                    "e","e","e","e","e","e","e","e","e","e","e",
	                    "i","i","i","i","i",
	                    "o","o","o","o","o","o","o","o","o","o","o","o"
	                    ,"o","o","o","o","o",
	                    "u","u","u","u","u","u","u","u","u","u","u",
	                    "y","y","y","y","y",
	                    "d",
	                    "A","A","A","A","A","A","A","A","A","A","A","A"
	                    ,"A","A","A","A","A",
	                    "E","E","E","E","E","E","E","E","E","E","E",
	                    "I","I","I","I","I",
	                    "O","O","O","O","O","O","O","O","O","O","O","O"
	                    ,"O","O","O","O","O",
	                    "U","U","U","U","U","U","U","U","U","U","U",
	                    "Y","Y","Y","Y","Y",
	                    "D","");
	                    
	    $str = str_replace($marTViet,$marKoDau,$str);
	    return $str;
	}

	static public function getTotalPage($count, $countPerPage = 10)
	{
		$totalPage = 0;
		if ($countPerPage > 0 && $count > 0)
		{
			$totalPage = ceil($count/$countPerPage);
		}
		return $totalPage;
	}

	static public function getHost()
	{
		$sfInstance = sfContext::getInstance();
		$host       = $sfInstance->getRequest()->getHost();
		return 'http://'.$host;
	}

	static public function getScriptName()
	{
		$sfInstance   = sfContext::getInstance();
		$sfScriptName = $sfInstance->getRequest()->getScriptName();
		if (strcmp('/index.php',$sfScriptName) == 0)
		{
			return '';
		}
		else
		{
			return  '/frontend_dev.php';
		}
	}

	static public function getUrlRoot()
	{
		$sfInstance = sfContext::getInstance();
		$host       = $sfInstance->getRequest()->getHost();
		$scriptName = $sfInstance->getRequest()->getScriptName();
	  
		return 'http://'.$host.$scriptName.'/';
	}

	static public function getHashingPath($itemValue, &$path, $itemPerDir, $numberOfDir)
	{
		$path = '';
		for ($i = 0; $i < $numberOfDir; $i++)
		{
		}
	}

	static public function  is_email($s)
	{
		if( $s =="" )
		{
			return false;
		}
		if (strpos($s, " "))
		{
			return false;
		}
		if( !strpos($s,"@"))
		{
			return false;
		}
		$i = 1;
		$len 	= strlen($s);
		if( !strpos($s,".") )
		{
			return false;
		}

		if(	strpos($s, ".."))
		{
			return false;
		}

		if(strpos( $s, "." ) == $len -1 )
		{
			return false;
		}

		$str = "aabcdefghikjlmnopqrstuvwxyz-@._0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		for( $j=0; $j< $len; $j++ )
		{
			if( strpos($str,$s[$j],1) == false)
			{
				return false;
			}
		}
		return true;
	}

	static public function  GenerateCheckNumString()
	{
		global $config;
		$CHECKNUM_CHARS_LEN = strlen($config['CHECKNUM_CHARS'])-1;
		$checkNum    = '';
		for( $i=0; $i < $config['CHECKNUM_LEN']; $i++)
		{
			$pos   = rand(0, $CHECKNUM_CHARS_LEN);
			$checkNum .= $config['CHECKNUM_CHARS'][$pos];
		}
		return $checkNum;
	}

	static public function  MakeSafeXML($input)
	{
	 return "<![CDATA[".$input."]]>";
	}

	static public function  MakeSafeXML2($input)
	{
	 return "<![CDATA[".Entity2NCR($input)."]]>";
	}


	static public function  IsValidUserName($username, $maxLength=50)
	{
		if ((!$username) || (strlen($username)==0) || (strlen($username)>$maxLength))
		return false;

		// username must starts with any char a-z only
		$regexp = "[A-Z]";
		$firstChar = substr($username, 0, 1);
		if (!eregi( $regexp, $firstChar ))
		{
			return false;
		}

		// valid pattern
		$regexp = "^[A-Z0-9._]+$";
		if (eregi( $regexp, $username ))
		{
			return true;
		}
		return false;
	}

	static public function getFlashObject()
	{
		return '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
				    codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0"
				    width="0" height="0" id="playerContainer" align="middle">
				    <param name="allowScriptAccess" value="sameDomain" />
				    <param name="movie" value="/flash/mp3Player.swf"/>
				    <param name="quality" value="high" />
				    <param name="bgcolor" value="#ffffff" />
				    <embed src="/flash/mp3Player.swf" quality="high"
				    bgcolor="#ffffff" width="0" height="0" name="playerContainer" id="playerContainer"
				    align="middle" allowScriptAccess="sameDomain" type="application/x-shockwave-flash"
				    pluginspage="http://www.macromedia.com/go/getflashplayer"/>
				</object>';
	}
	
	static public function getAge($birthdate)
	{
		if ($birthdate == '')
		return '';
			
		$dateArray = date_parse($birthdate);
		return date('Y') - $dateArray['year'] -
		(date('n') < (ltrim($dateArray['month'],'0') + (date('j') < ltrim($dateArray['day'],'0'))));
	}

	static public function getUpdateImage($type)
	{
		$imgRoot ="/images/";	
		$img = "";
		switch ( $type)
		{
		   case 1:
		   	$img = "blast_edit.gif";
		   	break;
		   case 2:	
		   	$img = "home_friend_request.png";
		   	break;
		   case 3:	
		   	$img = "icon_ringtone.gif";
		   	break;
		   case 4:
		   	$img = "comment.gif";
		   	break;
		   case 5:
		   	$img = "ringtone_vote.gif";
		   	break;
		   case 6:
		   	$img = "ringtone_down.gif";
		   	break;
		   case 7:
		   	$img = "home_info_change.png";
		   	break;
		   case 8:
		   	$img = "discuss2.gif";
		   	break;
		   case 9:
		   	$img = "friend_add.gif";
		   	break;
		   case 10:
		   	$img = "home_deny_friend.png";
		   	break;
		   case 11:
		   	$img = "friend_delete.gif";
		   	break;
		   case 14:
		   	$img = "ringtone_down.gif";
		   	break;
		   default:
		   	$img = "download.gif";
		   	break;
		}
		return $imgRoot.$img;
	}
	
	static public function getArtist($ringtone = null)
	{	
		$result = '';
		$ringtone['artist1Name']  = trim($ringtone['artist1Name']);
		$ringtone['artist2Name']  = trim($ringtone['artist2Name']);
		$ringtone['artist3Name']  = trim($ringtone['artist3Name']);
				
		if ($ringtone['artist1Id'] > 0 && strlen($ringtone['artist1Name']) > 0)
	    {
	        $result = link_to($ringtone['artist1Name'], 'artist/overview?artistName='.self::str_normalizer($ringtone['artist1Name']).'&id='.$ringtone['artist1Id'], array('class' => 'artist_names'));	        
	    }	
	    if ($ringtone['artist2Id'] > 0 && strlen($ringtone['artist2Name']) > 0)
	    {
	        $result .= ' - '.link_to($ringtone['artist2Name'], 'artist/overview?artistName='.self::str_normalizer($ringtone['artist2Name']).'&id='.$ringtone['artist2Id'], array('class' => 'artist_names'));
	    }	
	    if ($ringtone['artist3Id'] > 0 && strlen($ringtone['artist3Name'])> 0)
	    {
	        $result .= ' - '.link_to($ringtone['artist3Name'], 'artist/overview?artistName='.self::str_normalizer($ringtone['artist3Name']).'&id='.$ringtone['artist3Id'], array('class' => 'artist_names'));
	    }	
	    if ($result != '')
	    {
	        return $result;
	    }
		
	    return '';		
	}
	
	static public function echoTags($name, $count)
	{
		$url = link_to($name,'search/result?search_for='.$name);
		if($count >= 5)
		{
			echo '<span class="tag5 tag"> '.$url.' </span>';
		}
		elseif ($count >= 4)
		{
			echo '<span class="tag4 tag"> <a>'.$url.'</a> </span>';
		}
		elseif ($count >= 3)
		{
			echo '<span class="tag3 tag"> <a>'.$url.'</a> </span>';
		}
		elseif ($count >= 2)
		{
			echo '<span class="tag2 tag"> <a>'.$url.'</a> </span>';
		}
		else
		{
			echo '<span class="tag1 tag"> <a>'.$url.'</a> </span>';
		}
	}
	
	static public function checkEmail($email)
	{			
        if(preg_match('/^\w[-.\w]*@(\w[-._\w]*\.[a-zA-Z]{2,}.*)$/', $email, $matches))
        {
            if(function_exists('checkdnsrr'))
            {
                if(checkdnsrr($matches[1] . '.', 'MX')) return true;
                if(checkdnsrr($matches[1] . '.', 'A')) return true;
            }else{
                if(!empty($hostName))
                {
                    if( $recType == '' ) $recType = "MX";
                    exec("nslookup -type=$recType $hostName", $result);
                    foreach ($result as $line)
                    {
                        if(eregi("^$hostName",$line))
                        {
                            return true;
                        }
                    }
                    return false;
                }
                return false;
            }
        }
        return false;
	}
	
	//Check format of phone number
	static public function checkPhoneNumber($phoneNumber)	
	{		
		$result = new stdClass();
		$result->success = false;
		$result->error_code = 0;
		$result->phone = "";		
		$phoneNumber = trim($phoneNumber);
		$length 	= strlen($phoneNumber);
		if ($length > 0)
		{
			if (( $length < 10 ) || ( $length > 12 )) {
				$result->message = sfConfig::get('phone_wrong_num_chars');//"Số điện thoại phải có từ 10 đến 13 chữ số";
				$result->error_code = 7;
			}else 
			{
				for ( $i =0; $i < $length; $i++)
				{
					if (!is_numeric($phoneNumber[$i])) {
						$result->success = false;
						$result->error_code = 8;
						$result->message = sfConfig::get('phone_must_be_num');//"Số điện thoại chỉ được là các chữ số";
						break;
					}
				}
				if ($i == $length)
				{	
					if($phoneNumber[0] == '0')
					{
						$result->phone = "84".substr($phoneNumber,1,$length-1);
						$result->phone2 = substr($phoneNumber,1,$length-1);
						$result->success = true;
					}
					else if (($phoneNumber[0] == '8') && ($phoneNumber[1] == '4') && ($phoneNumber[2] != '0'))
					{						
						$result->success = true;
						$result->phone = $phoneNumber;
						$result->phone2 = substr($phoneNumber,2,$length-2);
					}
					else if (($phoneNumber[0] == '8') && ($phoneNumber[1] == '4') && ($phoneNumber[2] == '0'))
					{
						$result->phone = "84".substr($phoneNumber,3,$length-3);
						$result->phone2 = substr($phoneNumber,3,$length-3);
						$result->success = true;			
					}
					else
					{
						$result->success = false;
						$result->message = sfConfig::get('phone_not_begin_84');//"Số điện thoại phải bắt đầu với 84... hoặc 0...";
						$result->error_code = 9;
					}
				}
			}
		}else
		{
			$result->success = false;
		    $result->message = sfConfig::get('phone_not_empty');//"Số điện thoại bị bỏ trống";
		    $result->error_code = 10;	
		}
		return $result;
	}
	
	//Check if a telnum exists
	//$isDbQuery
	//	1: must query in DB
	//		$userId: except this user
	//	0: check format only	
	static public function checkPhoneNumber2($phoneNumber, $userId, $isDbQuery, $lenCheck)
	{
		//var_dump($userId);
		//var_dump($userId);
		$result = new stdClass();
		$result->success = false;
		$result->phone = "";
		$result->users = null;
		
		$phoneNumber = trim($phoneNumber);
		$length 	= strlen($phoneNumber);
		if ($length > 0)
		{
			if ($lenCheck != null)
			{
				if (( $length < 10 ) || ( $length > 12 )) {
					$result->message = sfConfig::get('phone_wrong_num_chars'); //"Số điện thoại phải là 11 chữ số";
					$result->error_code = 7;
					$result->success = false;
					return $result;
				}
			}
			
			//XEM LAI is_numeric: co the check ca string !!!
			for ( $i =0; $i < $length; $i++)
			{
				if (!is_numeric($phoneNumber[$i])) {
					$result->success = false;
					$result->message = sfConfig::get('phone_must_be_num'); //"Số điện thoại chỉ được là các chữ số";
					$result->error_code = 8;
					break;
				}
			}
			
			if ($i == $length)
			{	
				//Chuan hoa so dien thoai
				if($phoneNumber[0] == '0')
				{
					$result->phone = "84".substr($phoneNumber, 1, $length-1);
					$result->success = true;
				}
				else if (($phoneNumber[0] == '8') && ($phoneNumber[1] == '4') && ($phoneNumber[2] != '0'))
				{
					$result->success = true;
					$result->phone = $phoneNumber;
				}
				else if (($phoneNumber[0] == '8') && ($phoneNumber[1] == '4') && ($phoneNumber[2] == '0'))
				{
					$result->phone = "84".substr($phoneNumber, 3, $length-3);
					$result->success = true;
				}
				else
				{
					$result->success = false;
					$result->message = sfConfig::get('phone_not_begin_84');//"Số điện thoại phải bắt đầu với 84... hoặc 0...";
					$result->error_code = 9;
				}
				
				if ($result->success == true)
				{
					if ($isDbQuery != null)
					{
						//sfContext::getInstance()->getLogger()->err($result->phone);
						//Query DB to check if this fone exists
						$con = Propel::getConnection('myisam');
						$cr = new Criteria();
						$cr->add(UserPeer::PHONE , $result->phone);
						$user = UserPeer::doSelect($cr, $con); //Multiple records
						$cnt = count($user);
												
						if ($cnt != 0)
						{	
							if($cnt == 1)
							{
								//Check if userId is needed or not
								if ($userId != null)
								{
									if ($user[0]->getId() != $userId)
									{
										$result->success = false;
										$result->message = sfConfig::get('phone_1_other_used'); //"Đã có 1 user khác dùng số điện thoại này";
										$result->users = " ".$user[0]->getUserName();										
									}
									else
									{
										$result->success = true;
										$result->message = sfConfig::get('phone_current_num'); //"Số điện thoại hiện tại của chính người dùng";
									}
								}
								else
								{
									$result->success = false;
									$result->message = sfConfig::get('phone_1_other_used'); //"Đã có 1 user khác dùng số điện thoại này";
									$result->users = " ".$user[0]->getUserName();
								}
							}
							else
							{
								$result->success = false;
								$result->message = sfConfig::get('phone_more_than_1'); //"Có nhiều hơn 1 user đã có số điện thoại này";
								for($i=0; $i<$cnt; $i++)
								{
									$result->users = $result->users." ".$user[$i]->getUserName();
								}
							}
						}
						else
						{
							$result->success = true;
							$result->message = sfConfig::get('phone_no_other_used'); //"Chưa có người dùng nào có số điện thoại này";
						}
					}
					else
					{
						//Format of Phone num is okay
						$result->success = true;
						$result->message = sfConfig::get('phone_format_ok'); //"Số điện thoại có định dạng hợp lệ";
					}
				}
			}			
		}
		else
		{
			$result->success = false;
		    $result->message = sfConfig::get('phone_not_empty');
		    $result->error_code = 10;
		}
		return $result;
	}	
	
	static public function checkUserName($userName, $userId)
	{
		$userName = trim($userName);
		$result = new stdClass();
		$result->success = false;

		if ($userName)
		{
			if (ringring::IsValidUserName($userName))
			{
				//Query DB to check if this fone exists
				$con = Propel::getConnection('myisam');
				$cr = new Criteria();
				$cr->add(UserPeer::USERNAME , $userName);
				$user = UserPeer::doSelect($cr, $con); //Multiple records
				
				if (count($user) != 0)
				{
					if(count($user) == 1)
					{
						if ($userId != null)
						{
							if ($user[0]->getId() != $userId)
							{
								$result->success = false;
								$result->message = "Đã có 1 user khác dùng username này";
							}
							else
							{
								$result->success = true;
								$result->message = "Hợp lệ. Username của chính người dùng";
							}
						}
						else
						{
							$result->success = false;
							$result->message = "Đã có 1 user khác dùng username này";
						}
					}
					else
					{
						$result->success = false;
						$result->message = "Có nhiều hơn 1 user đã dùng username này";
					}
				}
				else
				{
					$result->success = true;
					$result->message = "Hợp lệ. Không tồn tại người dùng nào có username này";
				}
			}
			else
			{
				$result->sucess = false;
				$result->message = "Username có định dạng không hợp lệ";
			}
		}
		else
		{
			$result->sucess = false;
			$result->message = "Username không được bỏ trống";
		}		
		
		return $result;
	}
	
	function getTagSize($tagCount)
	{
		$tagcount_5 = sfConfig::get('tagcount_5');
		$tagcount_4 = sfConfig::get('tagcount_4');
		$tagcount_3 = sfConfig::get('tagcount_3');
		$tagcount_2 = sfConfig::get('tagcount_2');
		$tagcount_1 = sfConfig::get('tagcount_1');
		$tagSize ='';
		if($tagCount <= $tagcount_5)
		{
			$tagSize = 'tag5';
			return $tagSize;
		}
		elseif ($tagCount < $tagcount_4)
		{
			$tagSize = 'tag4';
			return $tagSize;
		}
		elseif ($tagCount < $tagcount_3)
		{
			$tagSize = 'tag3';
			return $tagSize;
		}
		elseif ($tagCount < $tagcount_2)
		{
			$tagSize = 'tag2';
			return $tagSize;
		}
		else
		{
			$tagSize = 'tag1';
			return $tagSize;
		}
	}

	static public function getPathStorage($rootDir, $itemId, $itemPerDir, $makeDir)
	{			
		$dir1 = floor($itemId / ($itemPerDir * $itemPerDir * $itemPerDir));
		$dir2 = floor(($itemId - $dir1 * $itemPerDir * $itemPerDir * $itemPerDir)/($itemPerDir * $itemPerDir));
		$temp = floor($itemId / ($itemPerDir * $itemPerDir));
		$dir3 = floor(($itemId -  $temp * $itemPerDir * $itemPerDir)/$itemPerDir);
			
		$path = $dir1 . "/" . $dir2 . "/" .$dir3;
		
		if (!file_exists($rootDir. "/" . $path) && ($makeDir))
		{
			if (!file_exists($rootDir. "/" . $dir1 . "/" . $dir2))
			{
				if (!file_exists($rootDir. "/" . $dir1))
				{
					mkdir($rootDir. "/" . $dir1, true);
				}
				mkdir($rootDir. "/" . $dir1 . "/" . $dir2, true);
				chmod($rootDir. "/" . $dir1, 0777 );
			}
			mkdir($rootDir. "/" . $dir1 . "/" . $dir2, true);
			chmod($rootDir. "/" . $dir1 . "/" . $dir2, 0777 );
		}
		mkdir($rootDir. "/" . $dir1 . "/" . $dir2 . "/" . $dir3, true);
		chmod($rootDir. "/" . $dir1 . "/" . $dir2 . "/" . $dir3, 0777 );
		return $path;
	}	
	
	static public function numberEncode($number,$shift_num = 6)
	{ 
		 $text = strval($number);
		 $nums = array('0','1','2','3','4','5','6','7','8','9');
		 $chars = array('t','a','z','b','i','c','q','d','r','f','g','o','h','y','j','s','k','u','m','v','n','x','l','p','w');
		 for($i=0; $i<10; $i++)
		 {  
		  $text = str_replace($nums[$i],$chars[$i+$shift_num],$text);
		 } 
		 $text = bin2hex($text); 
		 return $text;
	}
	
	static public function genMd5Password($len = 6)
	{
	    // function calculates 32-digit hexadecimal md5 hash
	    // of some random data
	    return substr(md5(rand().rand()), 0, $len);
	}
	
	static public function checkYMStatus($nick)
	{
		if(strlen($nick) < 4)
	    {
	        return sfConfig::get('sms_ym_nick_status');
	    }
	    
	    $nick =   strip_tags(trim($nick));
	    $nick =   preg_replace('/[^a-z0-9_.]+/i','',$nick);
	    $nick =   strtolower($nick);
	    $status = 'Offline';
	    
	    $checkWeb = file_get_contents( 'http://opi.yahoo.com/online?u='.urlencode( $nick ).'&m=t&t=1' );
	    if ($checkWeb == '01')
	    {
	    	$status = 'Online';
	    }
	    
	    return sprintf(sfConfig::get('sms_ym_nick_status'), $nick, $status);	    
	}
		
	static public function trim($str, $length)
	{		
		$str = trim($str);
	    if (strlen($str) <= $length)
	    {
	        return $str;
	    }
		$str = substr($str, 0, $length);
		$i = $length - 1;
	    while (($str[$i] != ' ' && $str[$i] != '-' && $str[$i] != '_' && $str[$i] != '(' && $str[$i] != ')')  && ($i > $length - 16))
	    {
	        $i--;
	    }
		if ($i < 16)
		{
			$shortStr = $str;
		}else
		{
	    	$shortStr = substr($str, 0, $i).'..';
		}
	    return $shortStr;
	}
	
	static public function getUrl($path)
	{
		$path = self::getHost().$path;
		return $path;
	}
	static public function showDescription($str, $length)
	{
	
	    $str = ltrim($str);
	    if (strlen($str)<= $length)
	    {
	        echo '<div id="full">'.$str.'</div>';
	        return ;
	    }
	    else
	    {  
	    	use_helper('MyString');
	        $shortStr = truncate($str, $length, '...', false, true);
	        echo "
	        <div id=\"short\" class =\"ringtone_info\">$shortStr
	        <a onclick=\"showFullText(true,'short','full'); return false;\" href=\"#\"> >> chi tiết </a>
	        </div>
	        <div id=\"full\" style=\"display:none\" class= \"ringtone_info\">$str
	        <a onclick=\"showFullText(false, 'short','full'); return false;\" href=\"#\"> <<</a>
	        </div>";
	
	    }
	}		
	
	static public function zoomImage($imgFile, &$width, &$height, &$rate)
	{
		list($Wu, $Hu) = getimagesize($imgFile);
        $Wd=400;
        $Hd=300;
        $Wr=0;
        $Hr=0;
        $R=1;
        if(($Wu / $Hu) >=($Wd / $Hd)) 
        {
            if ($Wu <= $Wd) 
            {
                $Wr = $Wu;
                $Hr = $Hu;
            }else if($Wu > $Wd) 
            {
                $Wr = $Wd;
                $Hr = ($Wd / $Wu)*$Hu;
                $R=$Wd / $Wu;
            }
        }else if (($Wu / $Hu) <($Wd / $Hd)) 
        {
            if($Hu <= $Hd) 
            {
                $Wr = $Wu;
                $Hr = $Hu;
            }else if($Hu > $Hd) 
            {
                $Hr = $Hd;
                $Wr= ($Hd / $Hu)*$Wu;
                $R=$Hd / $Hu;
            }
        }
        $width = $Wr;
        $height = $Hr;
        $rate = $R;
	}
	
	static public function getImageExtension($filename)
    {
        $ext  = @strtolower(@substr($filename, (@strrpos($filename, ".") ? @strrpos($filename, ".") + 1 : @strlen($filename)), @strlen($filename)));
        return ($ext == 'jpg') ? 'jpeg' : $ext;
    }
    
    static public function getStreamingUrl($type, $relPath)
    {
    	switch ($type)
    	{
    		case 'img_phone':
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_image_phone_dir_rel').'/'.$relPath;
    			
    		case 'img_user_large':
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_image_user_large_dir_rel').'/'.$relPath;
    			
    		case 'img_user_medium':
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_image_user_medium_dir_rel').'/'.$relPath;
    			
    		case 'img_user_small':
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_image_user_small_dir_rel').'/'.$relPath;
    			
    		case 'img_rt_large':
                return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_rt_thumbnail_large_dir_rel').'/'.$relPath;
                
            case 'img_rt_medium':
                return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_rt_thumbnail_medium_dir_rel').'/'.$relPath;
                
            case 'img_rt_small':
                return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_rt_thumbnail_small_dir_rel').'/'.$relPath;
    		
    		case 'img_artist':
                return sfConfig::get('rr_static_subdomain').$relPath;
    			
    		case 'img_temp':
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_image_temp_upload_dir_rel').'/'.$relPath;
    			
    		case 'origin':
    			return sfConfig::get('rr_media_subdomain').'/'.sfConfig::get('rr_origin_dir_rel').'/'.$relPath;
    		
    		case 'spectrum':
                return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_spectrum_dir_rel').'/'.$relPath;
    			
    		case 'mono':
    			return sfConfig::get('rr_media_subdomain').'/'.sfConfig::get('rr_mono_dir_rel').'/'.$relPath;
    			
    		case 'realtone':
    			return sfConfig::get('rr_media_subdomain').'/'.sfConfig::get('rr_realtone_dir_rel').'/'.$relPath;
    			
    		case 'upload':
    			return sfConfig::get('rr_media_subdomain').'/'.sfConfig::get('rr_upload_dir_rel').'/'.$relPath;
    			
    		case 'grp_origin': 
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_grp_origin_dir_rel').'/'.$relPath;
    			
    		case 'grp_image': 
    			return sfConfig::get('rr_static_subdomain').'/'.sfConfig::get('rr_grp_image_dir_rel').'/'.$relPath;
    			    			
    		default:
                return $relPath;    			
    			
    	}
    }

    static public function isRingtoneOfEvent($ringtoneId, $eventId)
    {
    	if (is_null($ringtoneId) || is_null($eventId))
    	{
    		return 0;
    	}
    	else
    	{
    		$con = Propel::getConnection('myisam');
    		$c = new Criteria();
    		$c->add(EventRingtonePeer::EVENT_ID, $eventId);
    		$c->add(EventRingtonePeer::RINGTONE_ID, $ringtoneId);
    		$rs = EventRingtonePeer::doSelectOne($c, $con);
    		if ($rs == null)
    			return 0;
    		else
    			return 1;
    	}
    }

    static public function nomalizeLongName($inputName, $length)
    {
    	$len = strlen($inputName);
		if ($len > $length)
		{
			$usrName1 = substr($inputName, 0, $length);
			$usrName2 = substr($inputName, $length, $len - $length);
			$usrName = $usrName1.' '.$usrName2;
		}
		else
			$usrName = $inputName;

		return $usrName;
    }

    static public function nomalizeKeyword($keyword)
    {
    	$arrKw = array('nhac chuong', 'ringtone', 'ca sy', 'nhac sy', 'ca si', 'nhac si');
		$count = count($arrKw);
		$total = 0;
		$word = $keyword;
		
		/*
    	for ($i = 0; $i<$count; $i++)
    	{
    		if (trim($word) != $arrKw[$i])
    		{
    			$word = str_replace($arrKw[$i], "", $word, &$total);
    		}
    	}
		*/
    	
    	return trim($word);    	
    }
    static public function CommentDecode($content)
	{
		$emoticon 		= array(
								'<img src="/css/emoticon/1.gif" alt="">',
								'<img src="/css/emoticon/2.gif" alt="">',
								'<img src="/css/emoticon/3.gif" alt="">',
								'<img src="/css/emoticon/4.gif" alt="">',
								'<img src="/css/emoticon/5.gif" alt="">',
								'<img src="/css/emoticon/6.gif" alt="">',
								'<img src="/css/emoticon/7.gif" alt="">',
								'<img src="/css/emoticon/8.gif" alt="">',
								'<img src="/css/emoticon/9.gif" alt="">',
								'<img src="/css/emoticon/10.gif" alt="">',
								'<img src="/css/emoticon/11.gif" alt="">',
								'<img src="/css/emoticon/12.gif" alt=""">',
								'<img src="/css/emoticon/13.gif" alt="">',
								'<img src="/css/emoticon/14.gif" alt="">',
								'<img src="/css/emoticon/15.gif" alt="">',
								'<img src="/css/emoticon/16.gif" alt="">',
								'<img src="/css/emoticon/17.gif" alt="">',
								'<img src="/css/emoticon/18.gif" alt="">',
								'<img src="/css/emoticon/19.gif" alt="">',
								'<img src="/css/emoticon/20.gif" alt="">',
								'<img src="/css/emoticon/21.gif" alt="">',
								'<img src="/css/emoticon/22.gif" alt="">',
								'<img src="/css/emoticon/23.gif" alt="">',
								'<img src="/css/emoticon/24.gif" alt="">',
								'<img src="/css/emoticon/25.gif" alt="">',
								'<img src="/css/emoticon/26.gif" alt="">',
								'<img src="/css/emoticon/27.gif" alt="">',
								'<img src="/css/emoticon/28.gif" alt="">',
								'<img src="/css/emoticon/29.gif" alt="">',
								'<img src="/css/emoticon/30.gif" alt="">',
								'<img src="/css/emoticon/31.gif" alt="">',
								'<img src="/css/emoticon/32.gif" alt="">',
								'<img src="/css/emoticon/33.gif" alt="">',
			                    '<img src="/css/emoticon/34.gif" alt="">',
								'<img src="/css/emoticon/35.gif" alt="">',
								'<img src="/css/emoticon/36.gif" alt="">',
								'<img src="/css/emoticon/37.gif" alt="">',
								'<img src="/css/emoticon/38.gif" alt="">',
								'<img src="/css/emoticon/39.gif" alt="">',
								'<img src="/css/emoticon/40.gif" alt="">',
								'<img src="/css/emoticon/41.gif" alt="">',
								'<img src="/css/emoticon/42.gif" alt="">',
								'<img src="/css/emoticon/43.gif" alt="">',
								'<img src="/css/emoticon/44.gif" alt="">',
								'<img src="/css/emoticon/45.gif" alt="">',
								'<img src="/css/emoticon/46.gif" alt="">',
								'<img src="/css/emoticon/47.gif" alt="">',
								'<img src="/css/emoticon/48.gif" alt="">',
		                        '<img src="/css/emoticon/49.gif" alt="">',
								'<img src="/css/emoticon/50.gif" alt="">',
								'<img src="/css/emoticon/51.gif" alt="">',
								'<img src="/css/emoticon/52.gif" alt="">',
								'<img src="/css/emoticon/53.gif" alt="">',
								'<img src="/css/emoticon/54.gif" alt="">',
								'<img src="/css/emoticon/55.gif" alt="">',
								'<img src="/css/emoticon/56.gif" alt="">',
								'<img src="/css/emoticon/57.gif" alt="">',
								'<img src="/css/emoticon/58.gif" alt="">',
								'<img src="/css/emoticon/59.gif" alt="">',
								'<img src="/css/emoticon/60.gif" alt="">',
								'<img src="/css/emoticon/61.gif" alt="">',
								'<img src="/css/emoticon/62.gif" alt="">',
		                        '<img src="/css/emoticon/63.gif" alt="">',
		                        '<img src="/css/emoticon/64.gif" alt="">',
								'<img src="/css/emoticon/65.gif" alt="">',
								'<img src="/css/emoticon/66.gif" alt="">',
								'<img src="/css/emoticon/67.gif" alt="">',
								'<img src="/css/emoticon/68.gif" alt="">',
								'<img src="/css/emoticon/69.gif" alt="">',
								'<img src="/css/emoticon/70.gif" alt="">',
		                        '<img src="/css/emoticon/71.gif" alt="">',
								'<img src="/css/emoticon/72.gif" alt="">',
								'<img src="/css/emoticon/73.gif" alt="">',
								'<img src="/css/emoticon/74.gif" alt="">',
								'<img src="/css/emoticon/75.gif" alt="">',
								'<img src="/css/emoticon/76.gif" alt="">',
								'<img src="/css/emoticon/77.gif" alt="">',
								'<img src="/css/emoticon/78.gif" alt="">',
								'<img src="/css/emoticon/79.gif" alt="">',
								'<img src="/css/emoticon/100.gif" alt="">',
								'<img src="/css/emoticon/101.gif" alt="">',
								'<img src="/css/emoticon/102.gif" alt="">',
								'<img src="/css/emoticon/103.gif" alt="">',
	                            '<img src="/css/emoticon/104.gif" alt="">',
								'<img src="/css/emoticon/105.gif" alt="">',
								'<img src="/css/emoticon/106.gif" alt="">',
								'<img src="/css/emoticon/107.gif" alt="">',
								'<img src="/css/emoticon/108.gif" alt="">'
		                        );
		$similarityText = array(
								':-)',
								':-(',
								';-)',
								':d',
								';;)',
								'>:D',
								':-/',
								':x',
								':->',
								':p',
								':-*',
								'=((',
								':-O',
								'X(',
								':>',
								'B-)',							
								':-s',							
								'#:-S',							
								'>:)',							
								':((',							
								':))',							
								':|',							
								'/:)',							
								'=))',							
								'O-)',							
								':-B',							
								'=;',
								'I-)',
								'8-|',
								'L-)',
								':-&',
								':-$',
								'[-(',
								':O)',
								'8-}',
								':-P',
								'(:|',
								'=P~',
								':-?',
								'#-o',
								'=D>',
								':-SS',
								'@-)',
								':^o',
								':-w',
								':-<',
								'>:P',
								'>(>',
								':@)',
							    '3:-O',
								':(|)',
								'~:>',
								'@};-',
								'%%-',
								'**==',
								'(~~)',
								'~O)',
								'*-:)',
								'8-X',
								'=:)',
								'>-)',
								':-L',	
								'[-O',
								'$-)',
								':-"',
								'b-(',
								':)>-',
								'[-X',
								'\:D/',
								'>:/',		
								';))',
								'o->',
								'o=>',
								'o-+',
								'(%)',
								':-@',
								'^:)^',
								':-j',
								'(*)',
								':)]',
								':-c',
								'~X-(',
								':-h',
								':-t',
								'8->',
								':-??',
								'%-(',
								':o3'
		                        );
								$content = str_replace($similarityText, $emoticon , $content);
								return $content;
	}
	
	static public function showInfo($localOrImuzik, $local, $imuzik)
	{
		if ($localOrImuzik)
			return $local;
		else
			return $imuzik;
	}
	
	static public function getTime($hour, $min, $sec)
	{
		$hour 	= ($hour < 10 ? "0".$hour : $hour);
		$min	= ($min < 10 ? "0".$min : $min);
		$sec	= ($sec < 10 ? "0".$sec : $sec);
		
		return $hour.":".$min.":".$sec;
	}

        static public function validViettelPhone($phone) {
            $ret = 0;
            $viettel = array('98', '97', '165', '166', '167', '168', '169', '164');
            $phone = trim($phone);

            $checkPhone = iring::checkPhoneNumber($phone);
            if ($checkPhone->success == true) {
                $phone = $checkPhone->phone;
                $head = substr($phone, 2, 3); //Lấy 3 ký tự đầu, bỏ "84"
                if (substr($head,0,1) != '1') {
                    $head = substr($head,0,2); //Lấy 2 ký tự đầu
                }
                if (in_array($head, $viettel)) {
                    $ret = $phone;
                }
            }
            return $ret;
        }
}


?>